/*
 * @Author: samfeng
 * @Date: 2021-04-18 11:52:15
 * @LastEditTime: 2021-05-01 22:31:52
 * @LastEditors: Please set LastEditors
 * @Description: 点餐界面的状态保持
 * @FilePath: /first_flutter_app/lib/controller/orderPageController.dart
 */
import 'package:get/get.dart';

class OrderController extends GetxController with SingleGetTickerProviderMixin {
  int pNum = 0;
  int iconActionIndex = 1;
  double amountTotal = 0.0;
  double inputTotal = 0.00;
  double hasPay = 0.00;
  String paymentStr = "现金";
  String inputTotalStr = "";
  String pageShowIndex = "personSetting";
  String orderStatus = '未生效';
  String servicePerson = '封云森';
  String orderPerson = '封云森';
  List selectProductList = [];
  bool showOrderDetails = false;
  List<Map> tableList = [];
  bool canDraggableTable = false;
  Map currentSelectTable = {
    "index": -1,
    "state": 1,
    "orderDetail":[]
  };
  bool selectShow = true;
  bool grayTitlediff = false;
  var currentAction = "wait"; // 当前操作动作
  var productListChangeColorsIndex = -1; // 改变已下单产品列的指定index的背景颜色
  int productOrderCount = 0;
  int currentSelectTableIndex = 0;
  int currentSelectOrderDetailsIndex = -1;
  bool showMoreFun = false;
  static OrderController get oc => Get.find();

  void setDraggableTable() {
    canDraggableTable = !canDraggableTable;
    update();
  }

  void setShowOrderDetails({int tableIndex, String clickType}) {
    if(null != tableIndex) {
      currentSelectTableIndex = tableIndex;
    }
    if(clickType == 'table') {
      if(showOrderDetails == false) {
        showOrderDetails = true;
      }
    }
    if(clickType == 'back') {
        showOrderDetails = false;
    }
    // showOrderDetails = !showOrderDetails;
    update();
  }

  void setTableList(List<Map> tList) {
    tableList = tList;
    update();
  }

  // 改变展示页面
  void switchLeftPage() {
    // ignore: unrelated_type_equality_checks
    if (pageShowIndex == "personSetting") {
      pageShowIndex = "orderPage";
      // ignore: unrelated_type_equality_checks
    } else if (pageShowIndex == "orderPage") {
      pageShowIndex = "personSetting";
    }
    update();
  }

  // 加人数
  void pluPNum() {
    pNum++;
    update();
  }

  //减人数
  void desPNum() {
    if (pNum > 0) pNum--;
    update();
  }

  void iconAction() {
    if (iconActionIndex >= 2) {
      iconActionIndex--;
    } else {
      iconActionIndex++;
    }
    update();
  }

  // 改变订单状态
  void setOrderStatus(String status) {
    orderStatus = status;
    grayTitlediff = !grayTitlediff;
    update();
  }

  void setServicePerson(String sp) {
    servicePerson = sp;
    update();
  }

  void setNoShowOrderDetails() {
    if (showOrderDetails) {
      showOrderDetails = false;
      update();
    }
  }

  void cleanTableOrderDetail() {
    tableList[currentSelectTableIndex]["orderDetail"] = [];
    tableList[currentSelectTableIndex]["state"] = 1;
    update();
  }

  void setOrderPerson(String op) {
    orderPerson = op;
    update();
  }

  // 点击菜品添加的时候进行判断
  void setSelectProductList(Map product) {
    var pid = product['id'];
    var addOrUpdate = false;
    var currentSelectProductList = tableList[currentSelectTableIndex]['orderDetail'];
    for (var p in currentSelectProductList) {
      if (p['id'] == pid) {
        p['qty'] += 1;
        p['price'] = p['qty'] * p['original_price'];
        addOrUpdate = true;
      }
    }
    if (!addOrUpdate) tableList[currentSelectTableIndex]['orderDetail'].add(product);
    amountTotal = computeAmountTotal();
    update();
  }

  void cleanSelectProductList(Map product) {
    selectProductList.clear();
    update();
  }

  void deleteSelectProductList() {
    var currentSelectProductList = [];
    if (!selectShow) {
      for (var po in selectProductList) {
        if (!po['selected']) currentSelectProductList.add(po);
      }
      if (currentSelectProductList.length <= 0) {
        selectProductList = [];
        selectShow = true;
        orderStatus = "未生效";
        grayTitlediff = false;
      } else {
        selectProductList = currentSelectProductList;
      }
      amountTotal = computeAmountTotal();
      update();
    }
  }

  void updateSelectProductList(int index) {
    var selectOrNo = false;
    for (var i = 0; i < selectProductList.length; i++) {
      if (i == index) {
        selectProductList[i]['selected'] = !selectProductList[i]['selected'];
        if (selectProductList[i]['selected']) selectOrNo = true;
      }
    }
    if (selectOrNo) {
      orderStatus = "可选择";
      grayTitlediff = true;
    }
    if (!selectOrNo) {
      if (selectProductList.length <= 0) {
        orderStatus = "未生效";
        grayTitlediff = false;
      }
    }
    update();
  }

  void setSelectShow() {
    selectShow = !selectShow;
    update();
  }

  void setGrayTitlediff() {
    grayTitlediff = !grayTitlediff;
    update();
  }

  void setCurrentAction(String action) {
    currentAction = action;
    update();
  }

  void setProductListChangeColorsIndex(int index) {
    currentSelectOrderDetailsIndex = index;
    // tableList[currentSelectTableIndex]['orderDetail'][index]['selected'] = true;
    // productListChangeColorsIndex = index;
    productOrderCount = tableList[currentSelectTableIndex]['orderDetail'][index]['qty'];
    update();
  }

  void cleanProductListChangeColorsIndex() {
    productListChangeColorsIndex = -1;
    productOrderCount = 0;
    if (selectProductList.length <= 0) amountTotal = 0.0;
    update();
  }

  void plusProductOrderCount() {
    productOrderCount += 1;
    /*
    if (productListChangeColorsIndex >= 0) {
      selectProductList[productListChangeColorsIndex]['qty'] =
          productOrderCount;
      selectProductList[productListChangeColorsIndex]['price'] =
          selectProductList[productListChangeColorsIndex]['original_price'] *
              productOrderCount;
    }
    */
    if (currentSelectTableIndex >= 0) {
      tableList[currentSelectTableIndex]['orderDetail'][currentSelectOrderDetailsIndex]['qty'] =
          productOrderCount;
      tableList[currentSelectTableIndex]['orderDetail'][currentSelectOrderDetailsIndex]['price'] =
          formatNum(tableList[currentSelectTableIndex]['orderDetail'][currentSelectOrderDetailsIndex]['original_price'] * productOrderCount, 2);
    }
    amountTotal = computeAmountTotal();
    update();
  }

  double formatNum(dynamic nums, int postion) {
    var num;
    double finalResult = 0;
    if (nums is double) {
      num = nums;
    } else {
      num = double.parse(nums.toString());
    }
    if ((num
        .toString()
        .length -
        num.toString().lastIndexOf(".") -
        1) <
        postion) {
      // print(num.toStringAsFixed(postion)
      //     .substring(0,
      //     num.toString().lastIndexOf(".") + postion + 1)
      //     .toString());
      finalResult = double.parse(num.toStringAsFixed(postion).substring(
          0, num.toString().lastIndexOf(".") + postion + 1).toString());
    } else {
      // print(num.toString()
      //     .substring(0,
      //     num.toString().lastIndexOf(".") + postion + 1)
      //     .toString());
      finalResult = double.parse(num.toString()
          .substring(0,
          num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
    return finalResult;
  }

  void desProductOrderCountBak() {
    if (productOrderCount <= 1) {
      if(productListChangeColorsIndex>=0) selectProductList.removeAt(productListChangeColorsIndex);
      productListChangeColorsIndex = -1;
      productOrderCount = 0;
    } else {
      productOrderCount -= 1;
      if (productListChangeColorsIndex >= 0) {
        selectProductList[productListChangeColorsIndex]['qty'] =
            productOrderCount;
        selectProductList[productListChangeColorsIndex]['price'] =
            selectProductList[productListChangeColorsIndex]['original_price'] *
                productOrderCount;
      }
    }
    amountTotal = computeAmountTotal();
    update();
  }


  void desProductOrderCount() {
    if (productOrderCount <= 1) {
      if(currentSelectTableIndex>=0) {
        tableList[currentSelectTableIndex]['orderDetail'].removeAt(currentSelectOrderDetailsIndex);
      }
      productOrderCount = 0;
    } else {
      productOrderCount -= 1;
      if (currentSelectTableIndex >= 0) {
        tableList[currentSelectTableIndex]['orderDetail'][currentSelectOrderDetailsIndex]['qty'] =
            productOrderCount;
        tableList[currentSelectTableIndex]['orderDetail'][currentSelectOrderDetailsIndex]['price'] =
            formatNum(tableList[currentSelectTableIndex]['orderDetail'][currentSelectOrderDetailsIndex]['original_price'] * productOrderCount, 2);
      }
    }
    amountTotal = computeAmountTotal();
    update();
  }

  double computeAmountTotal() {
    double pSum = 0;
    for (var p in tableList[currentSelectTableIndex]['orderDetail']) {
      pSum += p['original_price'] * p['qty'];
    }
    return formatNum(pSum, 2);
  }

  void updateAmountTotal(double amountTotal) {
    amountTotal = amountTotal;
    update();
  }

  void updatePaymentStr(String pyStr) {
    paymentStr = pyStr;
    update();
  }

  void updateInputTotal(String total) {
    inputTotal = double.parse(total);
    if(inputTotal > amountTotal) {
      inputTotal = amountTotal;
    }
    if(total == "0.0") {
      inputTotalStr = "";
    }
    update();
  }

  void contactInputTotal(String num) {
    inputTotalStr += num;
    double newTotal = double.parse(inputTotalStr);
    if (newTotal <= amountTotal) {
      inputTotal = double.parse(inputTotalStr);
    } else {
      inputTotalStr = amountTotal.toString();
      inputTotal = amountTotal;
    }
    update();
  }

  void backInputTotal() {
    if(inputTotalStr.length >= 2) {
      inputTotalStr = inputTotalStr.substring(0, inputTotalStr.length - 1);
      inputTotal = double.parse(inputTotalStr);
    } else {
      inputTotalStr = "";
      inputTotal = 0.0;
    }
    update();
  }

  void moLing() {
    String amountTotalStr = amountTotal.toString();
    List astList =  amountTotalStr.split(".");
    amountTotalStr = astList[0];
    amountTotal = double.parse(amountTotalStr);
    if(inputTotal > amountTotal) {
      inputTotal = amountTotal;
    }
    update();
  }
}
